<template>
<div class="editor-page">
  <div class="container page">
    <div class="row">

      <div class="col-md-10 offset-md-1 col-xs-12">
        <form @submit.prevent="onSubmit">
          <fieldset>
            <fieldset class="form-group">
                <input required :disabled="loading" v-model="article.title" type="text" class="form-control form-control-lg" placeholder="Article Title">
            </fieldset>
            <fieldset class="form-group">
                <input required :disabled="loading" v-model="article.description" type="text" class="form-control" placeholder="What's this article about?">
            </fieldset>
            <fieldset class="form-group">
                <textarea required :disabled="loading" v-model="article.body" class="form-control" rows="8" placeholder="Write your article (in markdown)"></textarea>
            </fieldset>
            <fieldset class="form-group">
                <input :disabled="loading" v-model='article.tagList' type="text" class="form-control" placeholder="Enter tags"><div class="tag-list"></div>
            </fieldset>
            <button :disabled="loading" class="btn btn-lg pull-xs-right btn-primary" >
                Publish Article
            </button>
          </fieldset>
        </form>
      </div>

    </div>
  </div>
</div>
</template>

<script>
import { createArticle, updateArticle } from '@/api/editor'

import { getArticle } from '@/api/article'

export default {

    middleware: 'authenticated',
    name:'editor',
    data() {
        return {
          article: {
            title: '',
            description: '',
            body: '',
            tagList: ''
          },
          loading: false
        };
    },
    async mounted () {
      if (this.$route.query.id){
        const { data } = await getArticle(this.$route.query.id)
        const { article } = data
        this.article = {
          title: article.title,
          description: article.description,
          body: article.body,
          tagList: article.tagList
        }
        // console.log(data)
      }
    },
    methods: {
      async onSubmit () {
        this.loading = true
        let info = null
        if (this.$route.query.id) {
          const { data } = await updateArticle(this.$route.query.id, {article: this.article })
          info = data
        } else {
          const { data } = await createArticle({article: this.article })
          info = data
        }
        this.loading = false
        this.$router.push(`/article/${info.article.slug}`)
      }
    }
};
</script>
